package cloud.tianai.mate.captcha.generator.impl;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.imageio.ImageIO;

public class MosaicImage {

    private static final int WIDTH = 600;
    private static final int HEIGHT = 360;
    private static final int BLOCK_SIZE = 20; // 马赛克块的大小
    private static final Color[] COLORS = {
            Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.ORANGE, Color.CYAN
    };
    private static final Random RANDOM = new Random();

    public static void main(String[] args) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        boolean[][] filled = new boolean[HEIGHT / BLOCK_SIZE][WIDTH / BLOCK_SIZE];
        int totalBlocks = (WIDTH / BLOCK_SIZE) * (HEIGHT / BLOCK_SIZE);

        // 初始化种子点列表
        Queue<int[]> seedQueue = new LinkedList<>();
        for (Color color : COLORS) {
            int seedX = RANDOM.nextInt(WIDTH / BLOCK_SIZE) * BLOCK_SIZE;
            int seedY = RANDOM.nextInt(HEIGHT / BLOCK_SIZE) * BLOCK_SIZE;
            seedQueue.add(new int[]{seedX, seedY, color.getRGB()});
        }

        while (!seedQueue.isEmpty() && totalBlocks > 0) {
            int[] seed = seedQueue.poll();
            int x = seed[0];
            int y = seed[1];
            int color = seed[2];

            if (!filled[y / BLOCK_SIZE][x / BLOCK_SIZE]) {
                fillRegion(g, x, y, new Color(color), filled, seedQueue);
                totalBlocks--;
            }
        }

        g.dispose();

        System.out.println(11);
    }

    private static void fillRegion(Graphics g, int startX, int startY, Color color, boolean[][] filled, Queue<int[]> seedQueue) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{startX, startY});
        filled[startY / BLOCK_SIZE][startX / BLOCK_SIZE] = true;
        g.setColor(color);
        g.fillRect(startX, startY, BLOCK_SIZE, BLOCK_SIZE);

        int[] dx = {0, 0, 1, -1};
        int[] dy = {1, -1, 0, 0};

        while (!queue.isEmpty()) {
            int[] point = queue.poll();
            int x = point[0];
            int y = point[1];

            for (int i = 0; i < 4; i++) {
                int newX = x + dx[i] * BLOCK_SIZE;
                int newY = y + dy[i] * BLOCK_SIZE;

                if (newX >= 0 && newX < WIDTH && newY >= 0 && newY < HEIGHT && !filled[newY / BLOCK_SIZE][newX / BLOCK_SIZE]) {
                    filled[newY / BLOCK_SIZE][newX / BLOCK_SIZE] = true;
                    g.fillRect(newX, newY, BLOCK_SIZE, BLOCK_SIZE);
                    queue.add(new int[]{newX, newY});
                    // 添加新的种子点到队列中以继续生长
                    seedQueue.add(new int[]{newX, newY, color.getRGB()});
                }
            }
        }
    }
}
